Repository navigation
fix(transport): fail pending requests promptly on oversized responses - #1552
matinsanei wants to merge 4 commits into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@connor4312 is on triage rotation this week and is the reviewer for this one. Labels come from the PR labeler. Please review the change. Automated triage. Labels are a first pass and the assigned maintainer has the final say. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5a66bad454
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
|
|
||
| if fields.has_method { fields.id } else { None } | ||
| let id = fields.id?; |
There was a problem hiding this comment.
Recover response IDs when the payload precedes them
When an oversized response puts a large result or error before id—a legal JSON-RPC key order—the retained 8 KiB prefix can end inside the payload before reaching the ID. This returns None, so receive discards the response and the matching request remains pending until its timeout. Recover the ID without depending on it appearing in the initial prefix.
Useful? React with 👍 / 👎.
| continue; | ||
| } | ||
| LineRead::Oversized(Some(OversizedMessage::Response(id))) => { | ||
| let error = ErrorData::invalid_request( |
There was a problem hiding this comment.
I reproduced this on 5a66bad with an Auto client and a valid server/discover reply whose ID comes before the payload. When the reply exceeds the local line limit, the generated -32600 makes the client send legacy initialize. If the peer closes, startup reports "discover and legacy initialize both failed," which hides the actionable size-limit error.
Could we carry the request ID and line limit through as a distinct local receive error? That would let us fail the matching call promptly, surface the size limit during startup, and preserve legacy fallback for a genuine -32600 from the peer.
|
Good catch @jonxsong, thanks. I added a per-process marker for oversized responses so Auto startup surfaces the size limit instead of falling back to legacy initialize, while keeping normal -32600 fallback intact. I also added a small tail scanner to recover response IDs when result or error comes before id, along with tests for both. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0a609dd56
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self.push_id_byte(b); | ||
| } else if self.phase == ScannerPhase::Key && self.depth == 1 { | ||
| if self.escape || b == b'\\' { | ||
| self.key_overflow = true; |
There was a problem hiding this comment.
Decode escaped keys in the late-response scanner
For an oversized response whose large result or error precedes a valid escaped top-level key such as "\u0069d": 123, this branch marks the key as overflowed, so finish_key never records the ID and finish() returns None; receive then drops the line and leaves the matching call pending until timeout. The new tail scanner added in this change only recognizes unescaped raw field names, so the late-ID fix still misses this valid JSON encoding.
Useful? React with 👍 / 👎.
connor4312
left a comment
There was a problem hiding this comment.
Thanks. Failing the pending call promptly is the right fix for #1513, and I found no correctness problems: the error is only produced locally and never written to the peer, the marker can't be spoofed, scanner memory stays bounded, and the #1471 request path still works. My one request is about how this error reaches callers (inline). The escaped-key gap Codex raised is fine as a follow-up: it falls back to the current behaviour, a timeout.
| Self::OVERSIZED_MESSAGE_MARKER.to_owned(), | ||
| Value::from(Self::oversized_message_token()), | ||
| ); | ||
| Self::invalid_request( |
There was a problem hiding this comment.
Please give this its own ServiceError instead of a -32600 McpError.
Today a caller gets ServiceError::McpError with code -32600 (Invalid Request). JSON-RPC defines that code as "the JSON sent is not a valid Request object", so it blames the caller's request when the real problem is a local limit on the response. From outside the crate:
is_oversized_message()ispub(crate), so the only way to recognise this error is to match on the message text.error.datacontains an unexplained randomu64underio.modelcontextprotocol/oversizedMessage.- Any user code that branches on
-32600will misread it. That's the same mistakediscover_startupneeded a special case for in this PR.
The transport-closed marker already has a pattern for this: service.rs:1851 turns error.is_transport_closed() into ServiceError::TransportClosed. Can we do the same here, e.g. ServiceError::ResponseTooLarge { max_line_length }? ServiceError is #[non_exhaustive], so adding a variant doesn't break anyone. discover_startup could then match on the variant instead of checking the marker. If a new variant is too much for this PR, please at least make the predicate public and use -32603, which is what transport_closed() uses.
| Value::from(Self::oversized_message_token()), | ||
| ); | ||
| Self::invalid_request( | ||
| format!("Incoming response exceeded the maximum line length ({max_line_length} bytes)"), |
There was a problem hiding this comment.
Nit: most people who hit #1513 have a legitimately large tool result, so please tell them how to raise the limit, e.g. "…exceeded the maximum line length ({max_line_length} bytes); raise it with AsyncRwTransport::with_max_line_length". Once #1522 lands, the TokioChildProcessBuilder option belongs in the message too.
|
Thanks for the review @connor4312. I added ServiceError::ResponseTooLarge and ClientInitializeError::ResponseTooLarge, switched the local error to -32603 carrying maxLineLength with the marker, and updated the message to mention AsyncRwTransport::with_max_line_length. I also updated the tail scanner to handle escaped keys and validate the full response line before routing. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a6506eaae4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self.oversized_line_prefix.clear(); | ||
| request_id | ||
| let late_response_id = std::mem::take(&mut self.oversized_response_scanner).finish(); | ||
| message.or_else(|| late_response_id.map(OversizedMessage::Response)) |
There was a problem hiding this comment.
Honor tail validation before routing a prefix-recovered response
If an oversized response has an id and the start of a large result in the retained prefix, but a duplicate top-level id appears in the discarded tail, prefix parsing returns Response(id) while the full-line scanner marks the message invalid and returns None. This or_else still selects the prefix result, so receive emits an oversized-response error for the first ID and can consume the wrong pending request instead of ignoring the malformed response. Do not use a prefix candidate when the tail scanner has rejected the message.
Useful? React with 👍 / 👎.
Summary
Addresses the client/caller hang in #1513 (complementary to #1522, which exposes
max_line_lengthonTokioChildProcessBuilder).Previously,
AsyncRwTransport::read_linediscarded oversized lines and only recovered a requestidwhenmethodwas present (and rejected any prefix containingresultorerror). As a result, when a server sent a response exceedingmax_line_length,AsyncRwTransport::receivedropped it silently and the pending request stayed in the responder pool until the caller's timeout.Changes
crates/rmcp/src/transport/async_rw.rs:oversized_message_from_prefix) to distinguishOversizedMessage::Request(id)fromOversizedMessage::Response(id)while still rejecting malformed JSON, duplicate fields, and messages mixingmethodwithresult/error.AsyncRwTransport::receive, when an oversized response with a recoverableidis encountered, return a localRxJsonRpcMessage::error(-32600, mentioningmax_line_length) for thatidwithout writing anything back to the peer. The pending caller fails promptly withServiceError::McpError, and the transport stays open for subsequent messages.crates/rmcp/tests/test_async_rw_max_line_length.rs:resultanderroroversized responses while nothing is written back to the peer.oversized_response_fails_pending_client_call_promptly_and_recoversto verify end-to-end withRoleClientthat an oversizedtools/callresponse fails promptly without hanging and a subsequent call on the same session succeeds.Verification
cargo fmt/cargo clippy -p rmcp --all-targets --all-features -- -D warningscargo test -p rmcp --lib --all-features(952 passed)cargo test -p rmcp --all-features --test test_async_rw_max_line_length(18 passed)